﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Web.UI.WebControls;

namespace Microsoft.BizTalk.BAM.Additions
{
    public partial class DisplayBAMReferenceXml : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check for parameters
            if (Request.QueryString.Count == 0) throw new ArgumentException("No parameters was supplied");

            // Needs the following paramters:    activityInstanceId, referenceType, activityName, docName
            // Get parameters
            string activityID = Request.QueryString["activityInstanceId"];
            Guid testGuid = Guid.Parse(activityID);

            string referenceType = Request.QueryString["referenceType"];
            testGuid = Guid.Parse(activityID);

            string activityName = Request.QueryString["activityName"];
            if (activityName.Length >= 50) throw new ArgumentException("Parameter 'activityName' cannot be longer than 50 characters");

            string docName = Request.QueryString["docName"];
            if (activityName.Length >= 50) throw new ArgumentException("Parameter 'docName' cannot be longer than 50 characters");
            
            // Get data from SQL - use SSO to store the connString in multiple deployment scenarios
            string connectionString = "Server=.;Integrated Security=SSPI;Database=BAMPrimaryImport;";
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("select [LongReferenceData] from [dbo].[bam_" + activityName + "_AllRelationships] where  [ActivityID]='" + activityID + "' and [ReferenceType]='" + referenceType + "'", cn);
                cn.Open();
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                rdr.Read();

                // Populate the asp:xml control
                xmlDisplayReferenceData.DocumentContent = rdr[0].ToString();
                if (docName == "AnyXMLMessage")
                    xmlDisplayReferenceData.TransformSource = Server.MapPath("DisplayAnyXMLMessage.xsl");
            }
        }
    }
}